<template>
  <div class="mt-3">
    <div v-if="replyTarget" class="mb-2 text-sm text-gray-600 flex items-center">
      <span>回复 @{{ replyTarget.author.name }}:</span>
      <button @click="cancelReply" class="ml-2 text-blue-600 text-xs hover:underline">取消回复</button>
    </div>

    <textarea ref="textareaRef" v-model="content"
      class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
      :placeholder="placeholder" rows="3" />

    <div class="flex justify-end gap-2 mt-2">
      <button @click="cancelReply"
        class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200">
        取消
      </button>
      <button @click="handleSubmit"
        class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50"
        :disabled="!content.trim()">
        {{ replyTarget ? '回复' : '发布' }}
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import type { Comment } from '~/types/comment'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '写下你的评论...'
  },
  replyTarget: {
    type: Object as () => Comment | null,
    default: null
  }
})

const emit = defineEmits(['submit', 'cancel', 'update:modelValue'])

const content = ref(props.modelValue)
const textareaRef = ref<HTMLTextAreaElement | null>(null)

onMounted(() => {
  textareaRef.value?.focus()
})

const handleSubmit = () => {
  emit('submit', content.value.trim())
  content.value = ''
}

const cancelReply = () => {
  emit('cancel')
}
</script>